package com.yunji.common.utils.uuid;

import com.yunji.common.utils.StringUtils;
import com.yunji.common.utils.TimeUtils;
import org.springframework.util.Assert;

/**
 * @Project: yunji-coffee
 * @Package:    com.yunji.common.utils.uuid
 * @Title:      SerialCode
 * @Description:
 * 流水号 年月日时分秒+5位序列号
 *
 * History:
 * Date                     Version     Author          Summary
 * ============================================================
 * 2024-04-15 11:52:46      V1.0        HuaAo       新建类
 */
public class SerialCode
{
    // 12位的序列号
    private long sequence = 1;

    //上次时间戳，初始值为负数
    private long lastTime = -1L;

    private static final long SEQUENCE_MASK = 99999L;


    public synchronized String nextId(int length)
    {
        long currentTime = Long.parseLong(TimeUtils.dateTimeNow());
        Assert.isTrue((currentTime >= lastTime), "生成失败");
        // 获取当前时间戳如果等于上次时间戳(同一毫秒内),则在序列号加一;否则序列号赋值为0,从0开始。
        if (lastTime == currentTime)
        {
            sequence = (sequence + 1) % SEQUENCE_MASK;
            if (sequence == 0) { currentTime = nextTimeMillis(lastTime); }
        }
        else
        {
            sequence = 0;
        }

        // 将上次时间戳值刷新
        lastTime = currentTime;
        // 返回指定长度字符串
        return lastTime + StringUtils.padl(sequence + 1, length);
    }

    /**
     * @Desc	获取下次时间戳
     * @Date	2023-11-20 10:02:00
     * @param	lastTimestamp 最后一次时间戳
     * @return	获取唯一时间戳
     */
    private long nextTimeMillis(long lastTimestamp)
    {
        long timestamp = Long.parseLong(TimeUtils.dateTimeNow());
        while (timestamp <= lastTimestamp)
        {
            timestamp = Long.parseLong(TimeUtils.dateTimeNow());
        }
        return timestamp;
    }
}
